package org.dromara.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.app.domain.AppSocialAuth;
import org.dromara.app.domain.vo.AppSocialAuthVo;
import org.dromara.app.domain.vo.AppUserVo;
import org.dromara.app.mapper.AppSocialAuthMapper;
import org.dromara.app.service.AppSocialAuthService;
import org.dromara.app.service.AppUserService;
import org.dromara.common.core.utils.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * App端第三方登录授权Service业务层处理
 *
 * @author ruoyi
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class AppSocialAuthServiceImpl extends ServiceImpl<AppSocialAuthMapper, AppSocialAuth> implements AppSocialAuthService {

    private final AppSocialAuthMapper baseMapper;
    private final AppUserService appUserService;

    /**
     * 查询App端第三方登录授权
     */
    @Override
    public AppSocialAuthVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 根据用户ID查询社交认证列表
     */
    @Override
    public List<AppSocialAuthVo> queryByUserId(Long userId) {
        LambdaQueryWrapper<AppSocialAuth> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AppSocialAuth::getUserId, userId)
                .eq(AppSocialAuth::getDelFlag, "0")
                .orderByDesc(AppSocialAuth::getCreateTime);
        return baseMapper.selectVoList(wrapper);
    }

    /**
     * 根据平台和openId查询社交认证
     */
    @Override
    public AppSocialAuth queryByPlatformAndOpenId(String platform, String openId) {
        if (StringUtils.isBlank(platform) || StringUtils.isBlank(openId)) {
            return null;
        }
        LambdaQueryWrapper<AppSocialAuth> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AppSocialAuth::getPlatform, platform)
                .eq(AppSocialAuth::getOpenId, openId)
                .eq(AppSocialAuth::getDelFlag, "0")
                .last("LIMIT 1");
        return baseMapper.selectOne(wrapper);
    }

    /**
     * 根据平台和unionId查询社交认证
     */
    @Override
    public AppSocialAuth queryByPlatformAndUnionId(String platform, String unionId) {
        if (StringUtils.isBlank(platform) || StringUtils.isBlank(unionId)) {
            return null;
        }
        LambdaQueryWrapper<AppSocialAuth> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AppSocialAuth::getPlatform, platform)
                .eq(AppSocialAuth::getUnionId, unionId)
                .eq(AppSocialAuth::getDelFlag, "0")
                .last("LIMIT 1");
        return baseMapper.selectOne(wrapper);
    }

    /**
     * 新增App端第三方登录授权
     */
    @Override
    public Boolean insertAppSocialAuth(AppSocialAuth appSocialAuth) {
        appSocialAuth.setDelFlag("0");
        appSocialAuth.setCreateTime(new Date());
        return baseMapper.insert(appSocialAuth) > 0;
    }

    /**
     * 修改App端第三方登录授权
     */
    @Override
    public Boolean updateAppSocialAuth(AppSocialAuth appSocialAuth) {
        appSocialAuth.setUpdateTime(new Date());
        return baseMapper.updateById(appSocialAuth) > 0;
    }

    /**
     * 删除App端第三方登录授权
     */
    @Override
    public Boolean deleteAppSocialAuthById(Long id) {
        AppSocialAuth appSocialAuth = new AppSocialAuth();
        appSocialAuth.setId(id);
        appSocialAuth.setDelFlag("2");
        appSocialAuth.setUpdateTime(new Date());
        return baseMapper.updateById(appSocialAuth) > 0;
    }

    /**
     * 根据用户ID删除社交认证
     */
    @Override
    public Boolean deleteByUserId(Long userId) {
        LambdaQueryWrapper<AppSocialAuth> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AppSocialAuth::getUserId, userId);
        List<AppSocialAuth> list = baseMapper.selectList(wrapper);
        if (list.isEmpty()) {
            return true;
        }

        AppSocialAuth updateEntity = new AppSocialAuth();
        updateEntity.setDelFlag("2");
        updateEntity.setUpdateTime(new Date());

        return baseMapper.update(updateEntity, wrapper) > 0;
    }

    /**
     * 更新访问令牌
     */
    @Override
    public Boolean updateAccessToken(Long id, String accessToken, Integer expireIn, String refreshToken) {
        AppSocialAuth appSocialAuth = new AppSocialAuth();
        appSocialAuth.setId(id);
        appSocialAuth.setAccessToken(accessToken);
        appSocialAuth.setExpireIn(expireIn);
        appSocialAuth.setRefreshToken(refreshToken);
        appSocialAuth.setUpdateTime(new Date());
        return baseMapper.updateById(appSocialAuth) > 0;
    }

    @Override
    public Boolean deleteByUserIdAndPlatform(Long userId, String platform) {
        LambdaQueryWrapper<AppSocialAuth> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AppSocialAuth::getUserId, userId)
                .eq(AppSocialAuth::getPlatform, platform)
                .eq(AppSocialAuth::getDelFlag, "0");
        return baseMapper.delete(wrapper) > 0;
    }

    @Override
    public AppUserVo selectUserByPlatformAndOpenId(String platform, String openId) {
        if (StringUtils.isBlank(platform) || StringUtils.isBlank(openId)) {
            return null;
        }

        // 根据平台和openId查询社交认证记录
        AppSocialAuth socialAuth = queryByPlatformAndOpenId(platform, openId);
        if (socialAuth == null || socialAuth.getUserId() == null) {
            return null;
        }

        // 根据userId查询用户信息
        return appUserService.queryById(socialAuth.getUserId());
    }

    @Override
    public void socialRegister(me.zhyd.oauth.model.AuthUser authUserData) {
        if (authUserData == null) {
            throw new org.dromara.common.core.exception.ServiceException("第三方用户信息不能为空");
        }

        String platform = authUserData.getSource();
        String openId = authUserData.getUuid();
        Long userId = org.dromara.common.satoken.utils.LoginHelper.getUserId();

        if (StringUtils.isBlank(platform) || StringUtils.isBlank(openId)) {
            throw new org.dromara.common.core.exception.ServiceException("第三方平台信息不完整");
        }

        log.info("开始绑定第三方账号，用户ID: {}, 平台: {}, openId: {}", userId, platform, openId);

        // 检查是否已经绑定过该第三方账号
        AppSocialAuth existingSocialAuth = queryByPlatformAndOpenId(platform, openId);
        if (existingSocialAuth != null) {
            if (!userId.equals(existingSocialAuth.getUserId())) {
                log.warn("第三方账号已被其他用户绑定，平台: {}, openId: {}, 绑定用户: {}", platform, openId, existingSocialAuth.getUserId());
                throw new org.dromara.common.core.exception.ServiceException("此第三方账号已经被其他用户绑定!");
            } else {
                log.info("第三方账号已绑定当前用户，无需重复绑定，平台: {}, openId: {}", platform, openId);
                return;
            }
        }

        // 检查当前用户是否已经绑定过该平台的账号
        List<AppSocialAuthVo> userSocialAuths = queryByUserId(userId);
        boolean alreadyBound = userSocialAuths.stream()
                .anyMatch(auth -> platform.equals(auth.getPlatform()));

        if (alreadyBound) {
            // 如果已经绑定过该平台，则更新绑定信息
            log.info("用户已绑定该平台账号，更新绑定信息，用户ID: {}, 平台: {}", userId, platform);
            AppSocialAuth updateAuth = userSocialAuths.stream()
                    .filter(auth -> platform.equals(auth.getPlatform()))
                    .map(vo -> {
                        AppSocialAuth auth = new AppSocialAuth();
                        auth.setId(vo.getId());
                        auth.setUserId(userId);
                        auth.setPlatform(platform);
                        auth.setPlatformUid(authUserData.getUuid());
                        auth.setOpenId(openId);
                        auth.setUnionId(authUserData.getToken() != null ? authUserData.getToken().getUnionId() : null);
                        auth.setAccessToken(authUserData.getToken() != null ? authUserData.getToken().getAccessToken() : null);
                        auth.setExpireIn(authUserData.getToken() != null ? authUserData.getToken().getExpireIn() : null);
                        auth.setRefreshToken(authUserData.getToken() != null ? authUserData.getToken().getRefreshToken() : null);
                        auth.setScope(authUserData.getToken() != null ? authUserData.getToken().getScope() : null);
                        return auth;
                    })
                    .findFirst()
                    .orElse(null);

            if (updateAuth != null) {
                boolean success = updateAppSocialAuth(updateAuth);
                if (success) {
                    log.info("更新第三方账号绑定成功，用户ID: {}, 平台: {}", userId, platform);
                } else {
                    log.error("更新第三方账号绑定失败，用户ID: {}, 平台: {}", userId, platform);
                    throw new org.dromara.common.core.exception.ServiceException("更新绑定信息失败");
                }
            }
        } else {
            // 新增绑定记录
            log.info("新增第三方账号绑定，用户ID: {}, 平台: {}", userId, platform);
            AppSocialAuth newAuth = new AppSocialAuth();
            newAuth.setUserId(userId);
            newAuth.setPlatform(platform);
            newAuth.setPlatformUid(authUserData.getUuid());
            newAuth.setOpenId(openId);
            newAuth.setUnionId(authUserData.getToken() != null ? authUserData.getToken().getUnionId() : null);
            newAuth.setAccessToken(authUserData.getToken() != null ? authUserData.getToken().getAccessToken() : null);
            newAuth.setExpireIn(authUserData.getToken() != null ? authUserData.getToken().getExpireIn() : null);
            newAuth.setRefreshToken(authUserData.getToken() != null ? authUserData.getToken().getRefreshToken() : null);
            newAuth.setScope(authUserData.getToken() != null ? authUserData.getToken().getScope() : null);

            boolean success = insertAppSocialAuth(newAuth);
            if (success) {
                log.info("新增第三方账号绑定成功，用户ID: {}, 平台: {}", userId, platform);
            } else {
                log.error("新增第三方账号绑定失败，用户ID: {}, 平台: {}", userId, platform);
                throw new org.dromara.common.core.exception.ServiceException("绑定第三方账号失败");
            }
        }
    }

}